﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UCS.XNA.Draughts.Boards;
using UCS.XNA.Draughts.People;
using UCS.XNA.Draughts.Pieces;
using UCS.XNA.Utils;

namespace UCS.XNA.Draughts.GameStates
{
    public class InGameState : IGameState
    {
        #region Attributes and Properties

        private Player _winner;
        public Player Winner
        {
            get { return _winner; }
        }

        private Board _board;
        public Board Board
        {
            get { return _board; }
            set { _board = value; }
        }

        #endregion

        #region Private Members

        private Rectangle _bounds;
        private Referee _referee;
        private SpriteFont _font;

        #endregion

        #region Events

        public event EventHandler Ended;

        #endregion

        #region Constructors

        public InGameState(Rectangle bounds)
        {
            _bounds = bounds;
            _board = new Board();
            _referee = new Referee(_board);
            _referee.AssignEvents();

            Players.BlackPlayer.Board = _board;
            Players.WhitePlayer.Board = _board;

            this.InitializeFont();
        }

        #endregion

        #region Public Methods

        public void Update(GameTime gameTime)
        {
            _board.Update(gameTime);
            _referee.Update(gameTime);

            if (_referee.Winner != null)
            {
                _winner = _referee.Winner;
                if (this.Ended != null)
                    this.Ended(this, new EventArgs());
            }
        }

        public void Draw(GameTime gameTime)
        {
            _board.Draw(gameTime);

            this.DrawCurrentPlayer();
        }

        #endregion

        #region Private Methods

        private void InitializeFont()
        {
            this._font = GameResources.Content.Load<SpriteFont>("Arial");
        }

        private void DrawCurrentPlayer()
        {
            string text = _referee.CurrentPlayer.Color == PieceColor.Black ? "Pretos" : "Brancos";
            Color color = _referee.CurrentPlayer.Color == PieceColor.Black ? Color.Black : Color.White;

            GameResources.SpriteBatch.Begin();
            GameResources.SpriteBatch.DrawString(this._font, text, new Vector2(500, 50), color);
            GameResources.SpriteBatch.End();
        }

        #endregion
    }
}
